/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action.retail;

import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;
import database.ProductDAO;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Product;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.validation.SkipValidation;

/**
 *
 * @author Thai Ha Cong
 */
@Namespace("/")
public class ProductAction extends ActionSupport implements ModelDriven<Product>, ServletResponseAware, ServletRequestAware {

    private Integer pid;
    private String pname;
    private Product product = new Product();
    private List<Product> recentlyViewedProducts;
    private List<Product> recommendedProducts;
    private ProductDAO productDAO = new ProductDAO();

    public ProductAction() {
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public List<Product> getRecentlyViewedProducts() {
        return recentlyViewedProducts;
    }

    public void setRecentlyViewedProducts(List<Product> recentlyViewedProducts) {
        this.recentlyViewedProducts = recentlyViewedProducts;
    }

    public List<Product> getRecommendedProducts() {
        return recommendedProducts;
    }

    public void setRecommendedProducts(List<Product> recommendedProducts) {
        this.recommendedProducts = recommendedProducts;
    }

    @Override
    @Action(value = "product/*/*", results = {
        @Result(name = "success", location = "/product.jsp"),
        @Result(name = "error", location = "/index.jsp")},
            params = {"pid", "{1}", "pname", "{2}"})
    @SkipValidation
    public String execute() throws Exception {
        this.product = productDAO.getProductFromProductId(pid);
        product.createSpecs();

        if ((pname.replaceAll("-", " ")).equals(product.getName().replaceAll("-", " "))) {
            this.recommendedProducts = productDAO.getRecommendedProducts(pid);
            this.recentlyViewedProducts = this.getRecentlyViewed();

            this.addViewedCookie("" + pid);

            return SUCCESS;
        }
        return ERROR;
    }

    @Override
    @VisitorFieldValidator(message = "", appendPrefix = false)
    public Product getModel() {
        return product;
    }
    protected HttpServletResponse servletResponse;

    @Override
    public void setServletResponse(HttpServletResponse hsr) {
        this.servletResponse = hsr;
    }
    protected HttpServletRequest servletRequest;

    @Override
    public void setServletRequest(HttpServletRequest hsr) {
        this.servletRequest = hsr;
    }

    public List<Product> getRecentlyViewed() {
        List<Product> result = new ArrayList<Product>();

        String viewString = null;
        //Load from cookie
        Cookie[] cookies = servletRequest.getCookies();

        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals("viewedList")) {
                    viewString = c.getValue();
                    //System.out.println(viewString);
                }
            }

            if (viewString != null) {
                String[] viewIds = viewString.split(",");

                for (int i = viewIds.length - 1; i >= 0; i--) {
                    String sid = viewIds[i];

                    if (!sid.equals("null")) {
                        result.add(productDAO.getProductFromProductId(Integer.parseInt(sid)));
                    }
                }
            }
        }

        return result;
    }

    public void addViewedCookie(String newid) {
        String viewString = null;

        Cookie[] cookies = servletRequest.getCookies();

        if (cookies != null) {
            //Load from cookie
            for (Cookie c : cookies) {
                if (c.getName().equals("viewedList")) {
                    viewString = c.getValue();
                }
            }
        }
        
        if (viewString != null) {
            String[] viewIds = viewString.split(",");
            List<String> idList = new ArrayList<String>();
            for (String s : viewIds) {
                if (!s.equals("null")) {
                    idList.add(s);
                }
            }

            if (!idList.contains(newid)) {
                if (idList.size() >= 4) {
                    idList.remove(0);
                }
            } else {
                idList.remove(newid);
            }

            idList.add(newid);

            viewString = "";
            for (String s : idList) {
                viewString = viewString + "," + s;
            }
            viewString = viewString.substring(1);
        } else {
            viewString = newid;
        }


        //Save to cookie
        Cookie viewedCookie = new Cookie("viewedList", viewString);
        viewedCookie.setMaxAge(60 * 60 * 24 * 365); // Make the cookie last a year
        viewedCookie.setDomain("localhost");
        viewedCookie.setPath("/");

        servletResponse.addCookie(viewedCookie);
    }
}